<template>
	<view class="main">
		<view class="body ">
			<view class="content flex flex-direction  justify-between">
				<view class="header">
					<image class="logo" :src="logoIcon" mode="aspectFill"></image>
				</view>
				<view class="box">
					<!-- #ifndef MP-WEIXIN -->
					<button class="cu-btn block bg-blue margin-tb-sm lg login" @click="toAuthLogin">
						<text v-if="btnLoading" class="cuIconfont-spin cuIcon-loading2"></text>
						微信授权登录
					</button>
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN -->
					<button class="cu-btn block bg-blue margin-tb-sm lg login" open-type="getUserInfo"
						@getuserinfo="toAuthLogin">
						<text v-if="btnLoading" class="cuIconfont-spin cuIcon-loading2"></text>
						微信授权登录
					</button>
					<!-- <button class="cu-btn block bg-blue margin-tb-sm lg login" @click="toAuthLogin1">
						<text v-if="btnLoading" class="cuIconfont-spin cuIcon-loading2"></text>
						微信授权登录
					</button>
					 -->
					
					<!-- <button class="cu-btn block bg-blue margin-tb-sm lg login" @tap="toAuthLogin1">
						<text v-if="btnLoading" class="cuIconfont-spin cuIcon-loading2"></text>
						微信授权登录11
					</button> -->
					<!-- #endif -->

					<button class="cu-btn block bg-white lg un-login" @click="noLogin">暂不登录</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var _this;
	import {
		mpWechatLogin,
		
	} from '@/api/login';
	export default {
		data() {
			return {
				logoIcon: this.$mAssetsPath.logo, //logo
				btnLoading: false,
				promoCodeParams: {} ,//注册码信息，用作标识的
				hasLogin:this.$mStore.getters.hasLogin,
				parent_id: '', //推荐人id
				
				isAuthUser: '', //是否授权过用户信息
				miniappcode: '',//uni.login获取的授权code
			};
		},
		mounted() {
			_this = this;
		},
		onLoad(option) {
			// #ifdef H5
			if (this.$mPayment.isWechat()) {
				this.isAuthLoginShow = true;
			}
			// #endif
			
			// 判断是否推荐好友连接过来的
			
			//先解析二维码内容
			
			let user_id = this.$mHelper.decodeScanParams(option);
			if(user_id ){
				this.parent_id = user_id;
				/* if(!this.hasLogin){
					// 新用户直接跳登录去绑定
					this.parent_id = user_id;
				} */
				
					
			}
			console.log('邀请好友',option, user_id,this.parent_id)
			
			
		
		
		},
		onShow() {
			let isLogin = this.$mStore.getters.hasLogin;
			// 已经登录
			console.log('登录状态', isLogin)
			if (isLogin) {
				this.$mRouter.reLaunch({
					route: this.$mRoutesConfig.main.path
				});
			}
		},

		methods: {
			toAuthLogin1() {
				 if(!uni.getUserProfile){
					 this.toAuthLogin();
					 return false;
				 }
				console.log("aaaa")
				let authApi = '';
				this.btnLoading = true;
				
				uni.getUserProfile({
					desc: '登录', // 这个参数是必须的  
					success: (infoRes) => {
						console.log(1111,infoRes);
						uni.login({
							provider: 'weixin',
							scopes: 'auth_user',
							success: function(loginRes) {
								console.log("新版获取用户信息!!", loginRes,infoRes);
								if(!infoRes.rawData){
									console.log("新版获取用户信息rawdata不存在", loginRes,infoRes);
									// _this.toAuthLogin();
								}
								let params = {};
								authApi = mpWechatLogin;
														
								params.raw_data = infoRes.rawData;
								params.encrypted_data = infoRes
									.encryptedData;
								params.iv = infoRes.iv;
								params.signature = infoRes.signature;
														
								params.code = loginRes.code;
								console.log('微信授权返回结果', params);
								_this.thirdPartyAuthLogin(authApi, params);
						
							},
							fail: function() {
								_this.$mHelper.toast('微信登录授权失败!');
								_this.btnLoading = false;
								_this.$mHelper.log('暂不支持小程序登录');
							}
						});
					},
					fail: err => {
						console.log(err)
					}
				})

			},
			// 授权登录
			toAuthLogin() {
				this.btnLoading = true;

				/*  #ifdef H5  */
				if (this.$mPayment.isWechat()) {
					const href = window.location.href;
					window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?
														appid=${this.$mConfig.weixinAppId}&
														redirect_uri=${href}&
														response_type=code&
														scope=snsapi_userinfo&
														state=STATE#wechat_redirect`;
				} else {
					this.$mHelper.toast('当前平台不支持授权登录');
					this.btnLoading = false;
				}
				/*  #endif  */
				let authApi;
				// #ifdef APP-PLUS
				// eslint-disable-next-line
				plus.oauth.getServices(
					function(services) {
						let weixinService;
						if (services && services.length) {
							for (let i = 0, len = services.length; i < len; i++) {
								if (services[i].id === 'weixin') {
									weixinService = services[i];
									break;
								}
							}
							if (!weixinService) {
								_this.$mHelper.toast('没有微信登录授权服务');
								return;
							}
							let group = 'group';
							if (uni.getSystemInfoSync().platform === 'android') {
								group = 'android';
							}
							weixinService.authorize(
								e => {
									authApi =
										`${thirdPartyWechatOpenPlatform}?code=${e.code || ''}&group=${group}&promo_code=${_this.promoCodeParams.promo_code || ''}`;
									_this.thirdPartyAuthLogin(authApi);
								},
								function(err) {
									// 授权失败 error
									_this.btnLoading = false;
									_this.$mHelper.toast(err.message.split(',')[0]);
								}
							);
						}
					},
					function() {
						// 获取 services 失败
						_this.btnLoading = false;
					}
				);
				// #endif
				// #ifdef MP-WEIXIN
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									console.log("新版获取用户信息111", loginRes);


											uni.getUserInfo({
												provider: 'weixin',
												success: function(infoRes) {
											console.log("老版获取用户信息",infoRes)
											
											let params = {};
											authApi = mpWechatLogin;

											params.raw_data = infoRes.rawData;
											params.encrypted_data = infoRes
												.encryptedData;
											params.iv = infoRes.iv;
											params.signature = infoRes.signature;

											params.code = loginRes.code;
											console.log('微信授权返回结果', params);
											_this.thirdPartyAuthLogin(authApi, params);
										},
										fail: err => {
											_this.$mHelper.toast('微信授权失败');
											console.log('授权失败', err)
											_this.btnLoading = false;
										}
									});
								},
								fail: function() {
									_this.$mHelper.toast('微信登录授权失败!');
									_this.btnLoading = false;
									_this.$mHelper.log('暂不支持小程序登录');
								}
							});
						} else {
							uni.showToast({
								title: '请先安装微信或升级版本',
								icon: 'none'
							});
						}
					}
				});
				// #endif
			},
			/**
			 * 第三方授权登录处理
			 */
			async thirdPartyAuthLogin(authApi, params = {}) {
				if(_this.parent_id){
					params.parent_id = _this.parent_id;
				}
				
				_this.$http
					.post(authApi, params)
					.then(async r => {
						console.log('微信登录！', r);
						_this.btnLoading = false;
						if (r.code === _this.sucCode) {
							console.log('微信登录2222！', r);
							let rData = r.data,
								userInfo = rData.userinfo;

							// 保存到缓存
							await _this.$mStore.commit('login', userInfo);

							_this.jump();


						} else {
							//授权失败
							_this.$mHelper.toast(r.msg);
						}




						
					})
					.catch((err) => {
						console.log('请求错误111', err);
					});
				
			},

			/**
			 * 跳转选择
			 */
			async jump() {
				let backToPage = _this.$mHelper.getBackPage();
				// console.log('上一个页面存在',uni.getStorageInfoSync('backToPage'));
				if (backToPage) {
					backToPage = JSON.parse(backToPage)
					let backUrl = backToPage.route || '';
					console.log('上一个页面存在', backToPage, backToPage.route, backUrl);
					if (_this.$mHelper.checkTabBarUrl(backUrl)) {
						_this.$mRouter.reLaunch(backToPage);
					} else {

						_this.$mRouter.redirectTo(backToPage);
					}
					await _this.$mHelper.removeBackPageStorage();

				} else {
					console.log('上一个页面不存在，直接跳转首页', backToPage);
					// 跳转首页
					_this.$mRouter.reLaunch({
						route: _this.$mRoutesConfig.main.path
					});
				}

			},
			/**
			 * 暂不登录，跳转首页
			 */
			noLogin() {
				/* let url = this.$mRoutesConfig.main.path;
				this.$mRouter.reLaunch({
					route: url
				}); */
				this.jump();
			}
		}
	};
</script>

<style lang="scss">
	.body {
		padding: 0 50rpx;

		.header {}

		.content {
			padding: 250rpx 30rpx 0;
		}
	}

	.header {
		.logo {
			display: block;
			width: 150rpx;
			height: 145rpx;
			margin: auto;
		}
	}

	.box {
		margin-top: 200rpx;

		button {
			margin-bottom: 60rpx;
		}

		.login {
			background: #ff5500;
		}

		.un-login {
			border: 1px solid #ff5500;
			color: #ff5500;
		}
	}
	
	.btn {
		height: 90rpx;
		line-height: 90rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
	}
	
	.cancel-btn {
		color: #999999 !important;
		font-weight: bold;
	}
	
	.get-user {
	
		.auth-btn {
	
			margin-bottom: 30rpx;
		}
	
		.phone-btn {
			border-radius: 50rpx;
		}
	
	}
	
	.get-phone {
		display: flex;
		align-items: center;
		justify-content: space-between;
		.btn{
			width:45%;
			// flex: 1 1 auto;
		}
	}
	
	.phone-login{
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 150rpx;
		.phone-title{
			margin-bottom: 20rpx;
			font-size: 30rpx;
			color: #999999;
		}
		.phone-logo{
			width: 64rpx;
			height: 64rpx;
		}
		
	}
</style>
